0919. 完全二叉树插入器【中等】
1. 📝 题目描述
完全二叉树 是每一层(除最后一层外)都是完全填充(即,节点数达到最大)的,并且所有的节点都尽可能地集中在左侧。
设计一种算法,将一个新节点插入到一棵完全二叉树中,并在插入后保持其完整。
实现 CBTInserter 类:
CBTInserter(TreeNode root)使用头节点为root的给定树初始化该数据结构;CBTInserter.insert(int v)向树中插入一个值为Node.val == val的新节点TreeNode。使树保持完全二叉树的状态,并返回插入节点TreeNode的父节点的值;CBTInserter.get_root()将返回树的头节点。
示例 1:

txt
输入
["CBTInserter", "insert", "insert", "get_root"]
[[[1, 2]], [3], [4], []]
输出
[null, 1, 2, [1, 2, 3, 4]]
解释
CBTInserter cBTInserter = new CBTInserter([1, 2]);
cBTInserter.insert(3); // 返回 1
cBTInserter.insert(4); // 返回 2
cBTInserter.get_root(); // 返回 [1, 2, 3, 4]1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
提示:
- 树中节点数量范围为
[1, 1000] 0 <= Node.val <= 5000root是完全二叉树0 <= val <= 5000- 每个测试用例最多调用
insert和get_root操作10^4次
2. 🎯 s.1 - BFS + 队列
js
/**
* @param {TreeNode} root
*/
var CBTInserter = function (root) {
this.root = root
this.queue = []
this.front = 0
// BFS 初始化,将所有未满的节点加入队列
const bfs = [root]
let i = 0
while (i < bfs.length) {
const node = bfs[i++]
if (node.left) bfs.push(node.left)
if (node.right) bfs.push(node.right)
if (!node.left || !node.right) {
this.queue.push(node)
}
}
}
/**
* @param {number} val
* @return {number}
*/
CBTInserter.prototype.insert = function (val) {
const newNode = new TreeNode(val)
const parent = this.queue[this.front]
if (!parent.left) {
parent.left = newNode
} else {
parent.right = newNode
this.front++
}
this.queue.push(newNode)
return parent.val
}
/**
* @return {TreeNode}
*/
CBTInserter.prototype.get_root = function () {
return this.root
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
- 时间复杂度:初始化
,插入 ,获取根节点 - 空间复杂度:
,存储未满子节点的队列
算法思路:
- 初始化时通过 BFS 遍历整棵树,将所有未满(左子节点或右子节点缺失)的节点加入队列
- 插入时取队列头部节点作为父节点:若左子节点为空则挂左边,否则挂右边并将该父节点出队
- 新节点始终入队,因为它是下一个可以挂子节点的候选